package com.hontech.kaltaapp.ui.parts

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.hontech.kaltaapp.R
import com.hontech.kaltaapp.device.event.DeviceStatus
import com.hontech.kaltaapp.ui.view.LabelState
import com.hontech.kaltaapp.ui.view.LabelTextView
import com.hontech.kaltaapp.utils.register
import com.hontech.kaltaapp.utils.unregister
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class TempParts (context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    private val tvName: TextView
    private val tvValue: LabelTextView
    private val tvIcValue: LabelTextView
    private val spSCV: LabelState
    private val spSCG: LabelState
    private val spOC: LabelState

    private val id: Int

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.parts_temp, this)
        tvName = view.findViewById(R.id.id_temp_tv_name)
        tvValue = view.findViewById(R.id.id_temp_lt_temp)
        tvIcValue = view.findViewById(R.id.id_temp_lt_ic_temp)
        spSCV = view.findViewById(R.id.id_temp_ls_scv)
        spSCG = view.findViewById(R.id.id_temp_ls_scg)
        spOC = view.findViewById(R.id.id_temp_ls_oc)

        val attr = context.obtainStyledAttributes(attrs, R.styleable.TempParts)
        id = attr.getInteger(R.styleable.TempParts_temp_id, 0)
        val name = attr.getString(R.styleable.TempParts_temp_name)
        attr.recycle()

        tvName.text = name
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onStatusUpdate(status: DeviceStatus) {
        val temp = if (id == 0) status.steam else status.water
        tvValue.set("${temp.value}℃")
        tvIcValue.set("${temp.internalValue}℃")
        spSCG.set(temp.scg)
        spSCV.set(temp.scv)
        spOC.set(temp.oc)
    }

    override fun onWindowVisibilityChanged(visibility: Int) {
        super.onWindowVisibilityChanged(visibility)
        if (visibility == VISIBLE) {
            register(this)
        } else {
            unregister(this)
        }
    }
}